<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工厂" prop="factoryId">
        <selectFactory v-model="queryParams.factoryId"></selectFactory>
      </el-form-item>
      <el-form-item label="生产车间" prop="workshopId">
        <selectWorkshop v-model="queryParams.workshopId"></selectWorkshop>
      </el-form-item>
      <el-form-item label="工作中心" prop="centerId">
        <selectCenter v-model="queryParams.centerId"></selectCenter>
      </el-form-item>
      <el-form-item label="生产工单" prop="moId">
        <el-input v-model="queryParams.moId" placeholder="请输入生产工单" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品信息" prop="itemId">
        <el-input v-model="queryParams.itemId" placeholder="请输入产品信息" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="申请单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入申请单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.WMS_RECEIVE_APPLY_STATUS)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['wms:receive-apply:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['wms:receive-apply:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="申请单号" align="center" prop="code" />
      <el-table-column label="工厂" align="center" prop="factoryId" />
      <el-table-column label="生产车间" align="center" prop="workshopId" />
      <el-table-column label="工作中心" align="center" prop="centerId" />
      <el-table-column label="生产计划" align="center" prop="planId" />
      <el-table-column label="生产工单" align="center" prop="moId" />
      <el-table-column label="产品信息" align="center" prop="itemId" />
      <el-table-column label="产品仓储信息" align="center" prop="itemWarehouseId" />
      <el-table-column label="配送位置" align="center" prop="address" />
      <el-table-column label="需求时间" align="center" prop="demandTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.demandTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领料方式" align="center" prop="applyType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.WMS_RECEIVE_TYPE" :value="scope.row.applyType" />
        </template>
      </el-table-column>
      <el-table-column label="领料套数" align="center" prop="applyCover" />
      <el-table-column label="领料数量" align="center" prop="applyAmount" />
      <el-table-column label="实际数量" align="center" prop="realAmount" />
      <el-table-column label="单位" align="center" prop="unitId" />
      <el-table-column label="仓库" align="center" prop="warehouseId" />
      <el-table-column label="库区" align="center" prop="areaId" />
      <el-table-column label="库位" align="center" prop="locationId" />
      <el-table-column label="制单人" align="center" prop="userId" />
      <el-table-column label="制单部门" align="center" prop="deptId" />
      <el-table-column label="处理人" align="center" prop="handleUserId" />
      <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.handleTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发料人" align="center" prop="sendUserId" />
      <el-table-column label="发料时间" align="center" prop="sendTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.sendTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="确认人" align="center" prop="confirmUserId" />
      <el-table-column label="确认时间" align="center" prop="confirmTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.confirmTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.WMS_RECEIVE_APPLY_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="说明" align="center" prop="description" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['wms:receive-apply:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['wms:receive-apply:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产工单" prop="moId">
              <el-input v-model="form.moId" placeholder="请输入生产工单" disabled>
                <el-button slot="append" icon="el-icon-search" @click="openSelectSingleMo = true"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工厂" prop="factoryId">
              <el-input v-model="form.factoryName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产车间" prop="workshopId">
              <el-input v-model="form.workshopName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作中心" prop="centerId">
              <selectCenter v-model="form.centerId"></selectCenter>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送位置" prop="address">
              <el-input v-model="form.address" placeholder="请输入配送位置" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="领料方式" prop="applyType">
              <el-select v-model="form.applyType" placeholder="请选择领料方式">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.WMS_RECEIVE_TYPE)"
                           :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料套数" prop="applyCover">
              <el-input type="number" v-model="form.applyCover" placeholder="请输入领料套数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="需求时间" prop="demandTime">
              <el-date-picker clearable v-model="form.demandTime" type="datetime" value-format="timestamp" placeholder="选择需求时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="form.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="说明" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" >
            <el-form-item label="领料明细">
              <el-checkbox-group v-model="checkList" @change="changeWarehouse">
                <el-checkbox v-for="(item, index) in warehouseList" :key="index" :label="item.warehouseId">{{item.warehouseName}}</el-checkbox>
              </el-checkbox-group>
              <el-table :data="bomInfo" ref="bomInfo" @selection-change="changSelect">
                <el-table-column type="selection" width="50" />
                <el-table-column label="序号" align="center" prop="sequencenumber" width="50" />
                <el-table-column label="品号" align="center" prop="itemCode" />
                <el-table-column label="品名" align="center" prop="itemName" />
                <el-table-column label="规格" align="center" prop="itemSpec" />
                <el-table-column label="用量" align="center" prop="requiredQty" width="50" />
                <el-table-column label="单位" align="center" prop="unitName" width="50" />
                <el-table-column label="仓库" align="center" prop="warehouseName" />
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查询   -->
    <SelectSingleMo :openSelectSingleMo.sync="openSelectSingleMoQuery" @selectSingleMo = "selectSingleMoQuery"></SelectSingleMo>
    <!-- 新增   -->
    <SelectSingleMo :openSelectSingleMo.sync="openSelectSingleMo" @selectSingleMo = "selectSingleMo"></SelectSingleMo>
  </div>
</template>

<script>
import { createReceiveApply, updateReceiveApply, deleteReceiveApply, getReceiveApply, getReceiveApplyPage, exportReceiveApplyExcel } from "@/api/wms/receiveApply";
import { getErpMoD } from '@/api/external/erpMoD'
import SelectFactory from '@/components/SelectFactory/index.vue'
import SelectWorkshop from '@/components/SelectWorkshop/index.vue'
import SelectCenter from '@/components/SelectCenter/index.vue'
import SelectSingleMo from '@/components/SelectSingleMo/index.vue'
import SelectItem from '@/components/SelectItem/index.vue'
import SelectWarehouse from '@/components/SelectWarehouse/index.vue'
import GenCode from '@/components/GenCode/index.vue'
import SelectUnit from '@/components/SelectUnit/index.vue'

export default {
  name: "ReceiveApply",
  components: {
    SelectFactory,
    SelectWorkshop,
    SelectCenter,
    SelectSingleMo,
    SelectItem,
    SelectWarehouse,
    GenCode,
    SelectUnit
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      //仓库列表
      warehouseList: [],
      checkList: [1],
      //工单bom详细
      bomInfo: [],
      // 总条数
      total: 0,
      // 领料申请单列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSelectSingleMoQuery: false,
      openSelectSingleMo: false,
      // 单号刷新
      refresh: undefined,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        code: null,
        factoryId: null,
        workshopId: null,
        centerId: null,
        moId: null,
        itemId: null,
        warehouseId: null,
        areaId: null,
        locationId: null,
        status: null,
        batchNo: null,
        createTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        factoryId: [{ required: true, message: "工厂不能为空", trigger: "blur" }],
        workshopId: [{ required: true, message: "生产车间不能为空", trigger: "blur" }],
        centerId: [{ required: true, message: "工作中心不能为空", trigger: "blur" }],
        planId: [{ required: true, message: "生产计划不能为空", trigger: "blur" }],
        moId: [{ required: true, message: "生产工单不能为空", trigger: "blur" }],
        address: [{ required: true, message: "配送位置不能为空", trigger: "blur" }],
        demandTime: [{ required: true, message: "需求时间不能为空", trigger: "blur" }],
        applyType: [{ required: true, message: "领料方式不能为空", trigger: "change" }],
        applyCover: [{ required: true, message: "领料套数不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getReceiveApplyPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    //查询工单
    selectSingleMoQuery(data){
      this.queryParams.moId = data.id;
      this.queryParams.moCode = data.code;
    },
    selectSingleMo(data){
      console.log(data)
      this.form.moId = data.id;
      this.form.moCode = data.code;
      this.form.planId = data.planId;
      this.form.planCode = data.planCode;
      this.form.itemName = data.itemName;
      this.form.workshopId = data.workshopId;
      this.form.workshopName = data.workshopName;
      this.form.batchNo = data.batchNo;
      this.form.inAmount = data.reportAmount;
      this.form.factoryId = data.factoryId;
      this.form.factoryName = data.factoryName;
      this.form.remark = data.remark;
      this.getErpMoDFun(this.form.planCode);
    },
    /** 查询工单单身 */
    getErpMoDFun(code){
      this.bomInfo = [];
      if (code !== null && code !== undefined) {
        getErpMoD(code).then(response => {
          response.data.sort((a, b) => {
            return a.warehouseId - b.warehouseId
          })
          this.bomInfo = response.data;
          this.getWarehouseList()
        })
      }
    },
    /** 获取仓库列表  */
    getWarehouseList(){
      this.warehouseList = [];
      const map = new Map();
      this.bomInfo.forEach(obj => {
        if (!map.has(obj.warehouseId)) {
          map.set(obj.warehouseId, obj);
          this.warehouseList.push(obj);
        }
      });
    },
    changeWarehouse(val) {
      this.$refs.bomInfo.clearSelection();
      this.bomInfo.forEach(item => {
        if (val.indexOf(item.warehouseId) !== -1) {
          this.$refs.bomInfo.toggleRowSelection(item,true)
        }
      })
    },
    changSelect(val) {
      this.form.bomList = val;
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        factoryId: undefined,
        workshopId: undefined,
        centerId: undefined,
        planId: undefined,
        moId: undefined,
        address: undefined,
        demandTime: undefined,
        applyType: undefined,
        applyCover: 0,
        batchNo: undefined,
        remark: undefined,
        description: undefined,
        bomList: [],
      };
      this.bomInfo = [];
      this.checkList = [];
      this.warehouseList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加领料申请单";
      this.refresh = new Date().getTime();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getReceiveApply(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改领料申请单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateReceiveApply(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createReceiveApply(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除领料申请单编号为"' + id + '"的数据项?').then(function() {
          return deleteReceiveApply(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有领料申请单数据项?').then(() => {
          this.exportLoading = true;
          return exportReceiveApplyExcel(params);
        }).then(response => {
          this.$download.excel(response, '领料申请单.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
